package com.lenovo.smarttraffic.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.ui.activity.Item1IntentActivity;
import com.lenovo.smarttraffic.ui.fragment.fgBean.AdapterBean;
import com.lenovo.smarttraffic.ui.fragment.fgBean.JsonBean;
import com.lenovo.smarttraffic.ui.fragment.fgBean.MotorwayNewBean;
import com.lenovo.smarttraffic.ui.fragment.fgBean.NewBean;
import com.lenovo.smarttraffic.ui.fragment.fgBean.RetrofitPostApi1;
import com.lenovo.smarttraffic.ui.fragment.fgBean.RetrofitPostApi2;
import com.lenovo.smarttraffic.ui.fragment.fgBean.RetrofitPostApi3;
import com.lenovo.smarttraffic.ui.fragment.fgBean.SpotNewBean;
import com.lenovo.smarttraffic.ui.fragment.fragmentAdapter.Fg1Adapter;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/*
 * zm
 */

public class FirstFragment extends BaseFragment {

    private ListView listView;
    private SharedPreferences sp_fg1;
    private String account;
    private String TAG = "FirstFragment";
    private List<AdapterBean> adapterBeanList;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    List<NewBean.ROWSDETAILBean> obj1 = (List<NewBean.ROWSDETAILBean>) msg.obj;
                    for (int i = 0; i < obj1.size(); i++) {
                        adapterBeanList.add(new AdapterBean(obj1.get(i).getTitle(), obj1.get(i).getCreatetime(), obj1.get(i).getContent(), "w"));
                    }
                    break;
                case 2:
                    List<MotorwayNewBean.ROWSDETAILBean> obj2 = (List<MotorwayNewBean.ROWSDETAILBean>) msg.obj;
                    for (int i = 0; i < obj2.size(); i++) {
                        adapterBeanList.add(new AdapterBean(obj2.get(i).getTitle(), obj2.get(i).getCreateTime(), obj2.get(i).getContent(), "w"));
                    }
                    break;
                case 3:
                    List<SpotNewBean.ROWSDETAILBean> obj3 = (List<SpotNewBean.ROWSDETAILBean>) msg.obj;
                    for (int i = 0; i < obj3.size(); i++) {
                        Date date = new Date();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = simpleDateFormat.format(date);
                        adapterBeanList.add(new AdapterBean(obj3.get(i).getName(), format, obj3.get(i).getInfo(), obj3.get(i).getImg()));
                    }
                    break;
                case 4:
                    List<NewBean.ROWSDETAILBean> obj4 = (List<NewBean.ROWSDETAILBean>) msg.obj;
                    for (int i = 0; i < 2; i++) {
                        adapterBeanList.add(new AdapterBean(obj4.get(i).getTitle(), obj4.get(i).getCreatetime(), obj4.get(i).getContent(), "w"));
                    }
                    mswipeRefreshLayout.setRefreshing(false);//关闭刷新
                    Toast toast = Toast.makeText(mActivity, "已经为您增加一组数据", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP, 0, 250);//放置Toast在顶部
                    toast.show();
                    break;
                case 5:
                    adapterBeanList.clear();
                    mswipeRefreshLayout.setRefreshing(false);//关闭刷新
                    Toast.makeText(mActivity, "没有数据", Toast.LENGTH_SHORT).show();
                    //null 加载失败
                    refreshPage(null);
                    break;
            }
            Collections.sort(adapterBeanList, new Comparator<AdapterBean>() {
                @Override
                public int compare(AdapterBean t0, AdapterBean t1) {
                    return (t0.getTime().compareTo(t1.getTime()));
                }
            });
            listView.setAdapter(new Fg1Adapter(mContext, adapterBeanList));
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Intent intent = new Intent(mContext, Item1IntentActivity.class);
                    Bundle bundle = new Bundle();
                    AdapterBean adapterBean = adapterBeanList.get(i);
                    bundle.putSerializable("fg1", (Serializable) adapterBean);
                    intent.putExtras(bundle);
                    intent.putExtra("classify", firsttab);
                    startActivity(intent);
                }
            });
        }

    };
    private List<SpotNewBean.ROWSDETAILBean> spotList;
    private List<MotorwayNewBean.ROWSDETAILBean> motorwayList;
    private List<NewBean.ROWSDETAILBean> newslist;
    private String firsttab;
    private SwipeRefreshLayout mswipeRefreshLayout;
    private String state = "";


    @Override
    protected View getSuccessView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            firsttab = bundle.getString("first");
        } else {
            firsttab = "";
        }
        View view = View.inflate(getActivity(), R.layout.fragment_first, null);
        sp_fg1 = getActivity().getSharedPreferences("LoginFlag", Context.MODE_PRIVATE);
        if (InitApp.isRegister) {
            account = sp_fg1.getString("account", "为记住密码");
            if (account.equals("为记住密码")) {
                account = InitApp.UserName;
            }
        } else {
            account = "user1";
        }
        adapterBeanList = new ArrayList<>();
        initView(view);
        initRefresh();
        return view;
    }

    private void initRefresh() {
        //下拉刷新的圆圈是否显示
        mswipeRefreshLayout.setRefreshing(false);
        //设置下拉时圆圈的颜色（可以由多种颜色拼成）
        mswipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright
        );
        //设置下拉时圆圈的背景颜色（这里设置成白色）
        mswipeRefreshLayout.setProgressBackgroundColorSchemeResource(
                android.R.color.white
        );
        //设置下拉刷新时的操作
        mswipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                retrofitRefresh();
            }
        });
    }


    private void initView(View view) {
        listView = view.findViewById(R.id.lv_fg);
        mswipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
    }

    private void retrofitRefresh() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitPostApi1 retrofitPostApi1 = retrofit.create(RetrofitPostApi1.class);
        Call<NewBean> call1 = retrofitPostApi1.getCall(new JsonBean("user1"));
        call1.enqueue(new Callback<NewBean>() {
            @Override
            public void onResponse(Call<NewBean> call, Response<NewBean> response) {
                newslist = response.body().getROWS_DETAIL();
                Message message = new Message();
                message.what = 4;
                message.obj = newslist;
                handler.sendMessageDelayed(message, 1000);
            }

            @Override
            public void onFailure(Call<NewBean> call, Throwable t) {
                Message message = new Message();
                message.what = 5;
                message.obj = null;
                handler.sendMessageDelayed(message, 1000);
            }
        });
    }

    private void retrofitPost1() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitPostApi1 retrofitPostApi1 = retrofit.create(RetrofitPostApi1.class);
        Call<NewBean> call1 = retrofitPostApi1.getCall(new JsonBean("user1"));
        call1.enqueue(new Callback<NewBean>() {
            @Override
            public void onResponse(Call<NewBean> call, Response<NewBean> response) {
                newslist = response.body().getROWS_DETAIL();
                Message message = new Message();
                message.what = 1;
                message.obj = newslist;
                handler.sendMessage(message);
                state = Constant.STATE_SUCCEED;
                retrofitPost2();
            }

            @Override
            public void onFailure(Call<NewBean> call, Throwable t) {
                state = Constant.STATE_FAILED;
            }
        });

    }

    private void retrofitPost2() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitPostApi2 retrofitPostApi2 = retrofit.create(RetrofitPostApi2.class);
        Call<MotorwayNewBean> call1 = retrofitPostApi2.getCall(new JsonBean("user1"));
        call1.enqueue(new Callback<MotorwayNewBean>() {
            @Override
            public void onResponse(Call<MotorwayNewBean> call, Response<MotorwayNewBean> response) {
                motorwayList = response.body().getROWS_DETAIL();
                Message message = new Message();
                message.what = 2;
                message.obj = motorwayList;
                handler.sendMessage(message);
                retrofitPost3();
            }

            @Override
            public void onFailure(Call<MotorwayNewBean> call, Throwable t) {

            }
        });
    }

    private void retrofitPost3() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.110:8088/transportservice/action/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitPostApi3 retrofitPostApi3 = retrofit.create(RetrofitPostApi3.class);
        Call<SpotNewBean> call1 = retrofitPostApi3.getCall(new JsonBean("user1"));
        call1.enqueue(new Callback<SpotNewBean>() {
            @Override
            public void onResponse(Call<SpotNewBean> call, Response<SpotNewBean> response) {
                spotList = response.body().getROWS_DETAIL();
                Message message = new Message();
                message.what = 3;
                message.obj = spotList;
                handler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<SpotNewBean> call, Throwable t) {
            }
        });
    }


    @Override
    public void refreshPage(Object o) {
        super.refreshPage(o);
        Log.e(TAG, "refreshPage: " + "=====");
    }

    @Override
    protected Object requestData() {
        retrofitPost1();
        Log.e(TAG, "requestData: " + state);
        SystemClock.sleep(1000);
        /*模拟请求服务器的延时过程*/
        //  Constant.STATE_SUCCEED;
        //  retrofitPost1();
        //  state=Constant.STATE_FAILED;
        return state;/*加载成功*/
    }


    @Override
    public void onClick(View view) {
    }

    /**
     * 类似于 Activity的 onNewIntent()
     * 注zm   TabLayout、ViewPager和Fragment之间的通讯
     */
    public static FirstFragment onNewBundle(String args) {
        FirstFragment firstFragment = new FirstFragment();
        Bundle bundle = new Bundle();
        bundle.putString("first", args);
        firstFragment.setArguments(bundle);
        return firstFragment;
    }

    //判断是否有网络连接
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
}
